package com.sinosoft.bee.services.consumer.demo.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * @author:TobbyQuinn
 * @date:2018/4/24
 * @project:bee
 **/
@RestController
public class Demo {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancer;

    /**
     * 添加断路器
     * @param id
     * @return
     */
    @GetMapping("consumer/{id}")
    @HystrixCommand(fallbackMethod = "getFallBack")
    public ResultVO get(@PathVariable Long id){
        ServiceInstance instance = loadBalancer.choose("bee-provider-demo");
        //URI beeProviderDemoUri = URI.create(String.format("http://%s:%s",instance.getHost(),instance.getPort()));
        URI beeProviderDemoUri = URI.create(String.format("http://%s",instance.getServiceId()));
        return restTemplate.getForObject(
                beeProviderDemoUri+"/provider/"+id,ResultVO.class);
    }

    public ResultVO getFallBack( Long id){
        return new ResultVO();
    }



    @GetMapping("consumer2/{id}")
    public ResultVO getRoundBalance(@PathVariable Long id){
//        ServiceInstance instance = loadBalancer.choose("bee-provider-demo2");
//
//        //URI beeProviderDemoUri = URI.create(String.format("http://%s:%s",instance.getHost(),instance.getPort()));
//        String str = String.format("http://%s:%s", instance.getHost(), instance.getPort());
//        System.out.println(str);
//        URI beeProviderDemoUri = URI.create(String.format("http://%s",instance.getServiceId()));
//        return restTemplate.getForObject(
//                beeProviderDemoUri+"/provider/"+id,ResultVO.class);
        return restTemplate.getForObject("http://bee-provider-demo2/provider/"+id,ResultVO.class);
    }
}
